package com.kyzh.core.pager.weal.accountbuy

import android.app.Activity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProviders
import androidx.lifecycle.observe
import androidx.recyclerview.widget.LinearLayoutManager
import com.gushenge.core.base.fragment.BaseFragment
import com.gushenge.core.beans.Deal
import com.kyzh.core.R
import com.kyzh.core.adapters.GameDetailDealAdapter
import com.kyzh.core.viewmodel.DealDynamicViewModel
import kotlinx.android.synthetic.main.recyclerview.*
import kotlinx.android.synthetic.main.titlebar.*
import org.jetbrains.anko.support.v4.toast

class DealDynamicFragment : BaseFragment() {
    private lateinit var viewModel: DealDynamicViewModel
    private lateinit var context: Activity
    private val arrays = arrayListOf<Deal>()
    private val adapter = GameDetailDealAdapter(R.layout.game_detail_deal_item, arrays)
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.activity_recyclerview, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        viewModel = ViewModelProviders.of(this).get(DealDynamicViewModel::class.java)
        context = requireActivity()
        initView()
        initData()
    }

    private fun initData() {
        viewModel.getData().observe(viewLifecycleOwner) {
            arrays.clear()
            arrays.addAll(it)
            adapter.notifyDataSetChanged()
        }
        viewModel.loadTimes().observe(viewLifecycleOwner) {
            root.finishLoadMore()
            root.finishRefresh()
        }
        viewModel.toast().observe(viewLifecycleOwner) {
            toast(it)
            root.finishLoadMore()
            root.finishRefresh()
            adapter.setEmptyView(R.layout.empty)
        }
    }

    private fun initView() {
        close.setOnClickListener { context.finish() }
        tvTitle.text = getString(R.string.dealDynamic)

        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.adapter = adapter

        root.setEnableAutoLoadMore(false)
        root.autoRefresh()
        root.setOnRefreshListener {
            viewModel.refresh()
        }
        root.setOnLoadMoreListener {
            viewModel.load()
        }
    }
}